<template>
    <div class="login-container">

        <el-form ref="loginFormRef" :model="form" label-width="80px" class="login-form" :rules="rules">
            <h2 class="login-title">登录</h2>
            <el-form-item label="账号" prop="username">
                <el-input v-model="form.username" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" placeholder="请输入密码" type="password" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit(loginFormRef)">登录</el-button>

            </el-form-item>
        </el-form>


    </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
// 引入路由
import { useRouter } from 'vue-router';
let $router = useRouter()
// 引入用户小仓库
import useUserStore from '@/store/modules/user';
let useStore = useUserStore()

// 消息提示组件
import { ElMessage } from 'element-plus';
const loginFormRef = ref();
const form = reactive({
    username: "",
    password: ''
})

// 用户自定义校验规则 rule规则，value：输入框输入的内容，callback如果校验失败就创建错误对象作为哦参数传入进去，从而提示，如果校验成功直接调用callback即可表示通过
const ValidateUsername = (_rules: any, value: any, callback: any) => {
    value = value.trim();
    // 获取输入长度
    const length = value && value.length;
    // 正则表达式
    const reg = /^[a-zA-Z0-9_]+$/;
    if (value === "") {
        callback(new Error("请输入用户名"));
    } else if (length < 4 || length > 12) {
        callback(new Error("长度在4-12间"));
    } else if (!reg.test(value)) {
        callback(new Error("用户名只能由英文，数字或者下划线组成"));
    } else {
        callback();
    }
}
// 表单校验规则
const rules = reactive<FormRules>({
    username: [
        {
            required: true,
            validator: ValidateUsername,
            trigger: ['blur', 'change']
        },

    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
        },
    ]
})

const onSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            try{
                // 登录成功
                await useStore.userLogin(form)
                // 编译式路由跳转到首页
                $router.push("/")
                // 提示登录成功
                ElMessage({
                    type:'success',
                    message:'登录成功'
                })
            }catch(error){
                // 登录失败的提示信息
                ElMessage({
                     type:'error',
                    message:(error as Error).message
                })
            }
        } else {
            console.log('error submit!');
        }
    });

};
</script>

<style scoped>
.login-form {
    width: 350px;
    margin: 160px auto;
    background: rgb(255, 255, 255, 0.8);
    padding: 30px;
    border-radius: 20px;
}

.login-container {
    position: absolute;
    width: 100%;
    height: 100%;
    background: url('../../assets/bg.jpg');

    overflow: hideden;
}

.login-title {
    text-align: center;
    color: #303133;
}
</style>